package com.ouman.luoliluoli;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ouman.luoliluoli.models.DaysModel;
import com.ouman.luoliluoli.utils.LocalSaveHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;


public class DaysBlankFragment extends Fragment {


    private OnFragmentInteractionListener mListener;
    private LocalSaveHelper saveHelper;
    private String STORAGE_FILENAME = "daysDataArray";
    private ArrayList<DaysModel> daysArrayList;

    private Integer daysDelta;
    private Integer newDaysDelta;

    private String choosenDate;
    private Boolean isClickedDate = false;


    public DaysBlankFragment() {
        // Required empty public constructor
    }


    public static DaysBlankFragment newInstance(String param1, String param2) {
        DaysBlankFragment fragment = new DaysBlankFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_days_blank, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        daysArrayList = new ArrayList<>();

        saveHelper = new LocalSaveHelper();
        FloatingActionButton mainFab = ((MainActivity) getActivity()).getFloatingActionButton();
        mainFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                View popDialogView = LayoutInflater.from(getContext()).inflate(R.layout.days_add_popup_dialog, null);
                final EditText editTextTitle = (EditText) popDialogView.findViewById(R.id.editTextTitle);
                final EditText editTextDesc = (EditText) popDialogView.findViewById(R.id.editTextDesc);

                final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setView(popDialogView);
                builder.setTitle("添加新日子");
                builder.setPositiveButton("添加", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (!isClickedDate){
                            Toast.makeText(getActivity(), "未选择日期", Toast.LENGTH_SHORT).show();
                        } else {
                            String title = editTextTitle.getText().toString();
                            String desc = editTextDesc.getText().toString();
                            DaysModel new_day = new DaysModel();
                            new_day.setTitle(title);
                            new_day.setDesc(desc);
                            new_day.setDate(choosenDate);
                            new_day.setDone(false);
                            new_day.setDaysDelta(daysDelta);
                            // 不是保存DayModel这个类，而是保存一个列表，大哥
                            daysArrayList.add(0, new_day);
                            System.out.println(daysArrayList.size());
                            saveHelper.saveToInternalStorage(daysArrayList, STORAGE_FILENAME, getActivity(), Context.MODE_PRIVATE);
                            // 保存之后通知recycle view刷新数据
                            Toast.makeText(getContext(), "添加成功", Toast.LENGTH_SHORT).show();
                            getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_main,
                                    new DaysFragment()).commit();
                            isClickedDate = false;
                        }
                    }
                });
                builder.show();

                Calendar cal = Calendar.getInstance();
                final Integer year = cal.get(Calendar.YEAR);
                final Integer month = cal.get(Calendar.MONTH);
                final Integer day = cal.get(Calendar.DAY_OF_MONTH);


                final TextView date = (TextView) popDialogView.findViewById(R.id.date);
                date.setText("今天是: " + year + "-" + (month+1) + "-" + day);
                Button dateChoose = (Button) popDialogView.findViewById(R.id.buttonDateChoose);
                dateChoose.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new DatePickerDialog(getActivity(),
                                new DatePickerDialog.OnDateSetListener() {
                                    @Override
                                    public void onDateSet(DatePicker view, int year, int month, int day) {
                                        // TODO Auto-generated method stub
                                        int mYear = year;
                                        int mMonth = month;
                                        int mDay = day;
                                        // 更新EditText控件日期 小于10加0
                                        date.setText(new StringBuilder()
                                                .append("执行日期: ")
                                                .append(mYear)
                                                .append("-")
                                                .append((mMonth + 1) < 10 ? "0"
                                                        + (mMonth + 1) : (mMonth + 1))
                                                .append("-")
                                                .append((mDay < 10) ? "0" + mDay : mDay));
                                        String dateString = mYear + "-" + (mMonth+1) + "-" + mDay + " " + "12:59:59";
                                        System.out.println(dateString);
                                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        Calendar c = Calendar.getInstance();
                                        Date dateNow = c.getTime();
                                        try{
                                            Date date1 = format.parse(dateString);
                                            daysDelta = differentDaysByMillisecond(dateNow, date1);
                                            if(daysDelta < 0){
                                                Toast.makeText(getActivity(), "所选日期已经过去了哟, 此为无效日期", Toast.LENGTH_SHORT).show();
                                            } else {
                                                choosenDate = mYear + "-" + (mMonth+1) + "-" + mDay + " " + "12:59:59";
                                                System.out.println("date!! delta: " + daysDelta);
                                                isClickedDate = true;
                                            }
                                        } catch (ParseException e){

                                        }

                                    }
                                }, year, month, day).show();
                    }
                });


            }
        });
    }

    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
        return days;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
